package b3.model
{
	import b3.net.*;
	import b3.util.*;
	
	public class FriendList extends Model
	{
		public var friendIds:Array;
		
		public function FriendList()
		{
			super();
			friendIds = new Array();
		}
		
		public function loadFriends(force:Boolean = false):void
		{
			var pm:PlayerManager = PlayerManager.getInstance();
			var serverRequest:ServerRequest = new ServerRequest(ServerEvent.GET_FRIENDS, {openid:pm.openid, openkey:pm.openkey, pf:pm.pf});
			serverRequest.setHandleFunc(handleLoadFriends);
			serverRequest.post(force);
		}
		
		public function handleLoadFriends(data:Object):void
		{
			friendIds = new Array();
			for (var s:String in data)
			{
				var userId:int = data[s]['userId'];
				var friend:Player = PlayerManager.getInstance().createPlayer(userId);
				friend.loadbyObject(data[s]);
				friendIds.push(friend.userId);
			}
			if (friendIds.indexOf(PlayerManager.getInstance().myUserId) < 0)
				friendIds.push(PlayerManager.getInstance().myUserId);
			friendIds.sort(sortFriends);
			dispatchEvent(new ModelEvent(ModelEvent.REFRESH_FRIEND_LIST));
		}
		
		
		private function sortFriends(a:int, b:int):int
		{
			var players:Object = PlayerManager.getInstance().players;
			var friendA:Player = players[a];
			var friendB:Player = players[b];
			if (friendA.historyMaxPopulation > friendB.historyMaxPopulation)
			{
				return -1;
			}
			else if (friendA.historyMaxPopulation < friendB.historyMaxPopulation)
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
	}
}